
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yozeev.Common;
using NPOI.SS.Util;
using Yozeev.Help;
using Abp.Authorization.Users;

namespace Yozeev.BusinessLogic
{
    /// <summary>
    /// TicketPrice应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TicketPriceAppService : YozeevAppServiceBase, ITicketPriceAppService
    {
        private readonly IRepository<TicketPrice, Guid> _entityRepository;

		private readonly IRepository<Ticket, Guid> _ticketRepository;

		private readonly ITicketPriceManager _entityManager;

		private readonly IQueryHelper _queryHelper;

		private readonly IRepository<Schedule, Guid> _scheduleRepository;

		private readonly IRepository<Wharf, Guid> _wharfRepository;

		private readonly IRepository<Boat, Guid> _boatRepository;

		private readonly IRepository<Route, Guid> _routeRepository;

		/// <summary>
		/// 构造函数 
		///</summary>
		public TicketPriceAppService(
        IRepository<TicketPrice, Guid> entityRepository
        ,ITicketPriceManager entityManager
			, IRepository<Ticket, Guid> ticketRepository
			, IRepository<Schedule, Guid> scheduleRepository
			, IRepository<Wharf, Guid> wharfRepository
			, IRepository<Boat, Guid> boatRepository
			, IRepository<Route, Guid> routeRepository
			, IQueryHelper queryHelper
		)
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
			_ticketRepository = ticketRepository;
			_queryHelper = queryHelper;
			_scheduleRepository = scheduleRepository;
			_wharfRepository = wharfRepository;
			_boatRepository = boatRepository;
			_routeRepository = routeRepository;
		}


        /// <summary>
        /// 获取TicketPrice的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[HttpPost,HttpGet]
        public async Task<PagedResultDto<TicketPriceListDto>> GetPaged(GetTicketPricesInput input)
		{

            var expression = _queryHelper.WhereExp<TicketPrice>(input.queryData);
			if (AbpUserBase.AdminUserName != GetCurrentUser().UserName)
				expression = _queryHelper.SetWhereExp<TicketPrice>(expression, GetViewTypeEnum<TicketPrice>(), await GetBranchUser());
			var query = from ticketprice in _entityRepository.GetAll().AsNoTracking()
                        .Where(expression)
                        select new
                        {
                            ticketprice,
                            ticketprice.Ticket,
                            ticketprice.Branch,
                            ticketprice.CreatorUser
                        };
            var list = new List<TicketPriceListDto>();
            query.ToList().ForEach(temp => {
                var _entity = temp.ticketprice.MapTo<TicketPriceListDto>();
				_entity.Ticket = temp.Ticket;
				_entity.WarePositionName = L(_entity.WarePosition.ToString());
				list.Add(_entity);
            });
            // TODO:根据传入的参数添加过滤条件
            var count = list.Count();
			list = list.AsQueryable().OrderBy(input.Sorting)
					.PageBy(input)
					.ToList();
			//         var count = await query.CountAsync();

			//var entityList = await query
			//		.OrderBy(input.Sorting).AsNoTracking()
			//		.PageBy(input)
			//		.ToListAsync();

			// var entityListDtos = ObjectMapper.Map<List<TicketListDto>>(entityList);
			//var entityListDtos = list.MapTo<List<TicketPriceListDto>>();

            return new PagedResultDto<TicketPriceListDto>(count, list);
		}


		/// <summary>
		/// 通过指定id获取TicketPriceListDto信息
		/// </summary>
		public async Task<TicketPriceListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TicketPriceListDto>();
		}

		/// <summary>
		/// 获取编辑 TicketPrice
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetTicketPriceForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetTicketPriceForEditOutput();
TicketPriceEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TicketPriceEditDto>();

				//ticketPriceEditDto = ObjectMapper.Map<List<ticketPriceEditDto>>(entity);
			}
			else
			{
				editDto = new TicketPriceEditDto();
			}

			output.TicketPrice = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TicketPrice的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateTicketPriceInput input)
		{
            input.TicketPrice.SetTime();
            if (input.TicketPrice.Id.HasValue)
			{
				await Update(input.TicketPrice);
			}
			else
			{
				await Create(input.TicketPrice);
			}
		}


		/// <summary>
		/// 新增TicketPrice
		/// </summary>
		protected virtual async Task<TicketPriceEditDto> Create(TicketPriceEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            // var entity = ObjectMapper.Map <TicketPrice>(input);
            var entity=input.MapTo<TicketPrice>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TicketPriceEditDto>();
		}

		/// <summary>
		/// 编辑TicketPrice
		/// </summary>
		protected virtual async Task Update(TicketPriceEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TicketPrice信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TicketPrice的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		/// <summary>
		/// 导出TicketPrice为excel表,等待开发。
		/// </summary>
		/// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}


		/// <summary>
		/// 航班审核
		///</summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<PagedResultDto<TicketPriceListDto>> GetPagedForSchedule(GetTicketPricesInput input)
		{
			var expression = _queryHelper.WhereExp<TicketPrice>(input.queryData);
			var query = from ticketprice in _entityRepository.GetAll().AsNoTracking()
                        .Where(expression)
						select new 
						{
                            ticketprice,
                            ticketprice.Ticket,
                            ticketprice.Branch,
                            ticketprice.CreatorUser
                        };
            var list = new List<TicketPrice>();
            query.ToList().ForEach(temp => {
                var _schedule = temp.ticketprice;
                _schedule.Ticket = temp.Ticket;
                list.Add(_schedule);
            });
            // TODO:根据传入的参数添加过滤条件
            var count = list.Count();
			list = list.AsQueryable().OrderBy(input.Sorting)
					.PageBy(input)
					.ToList();
			//         var count = await query.CountAsync();

			//var entityList = await query
			//		.OrderBy(input.Sorting).AsNoTracking()
			//		.PageBy(input)
			//		.ToListAsync();

			// var entityListDtos = ObjectMapper.Map<List<TicketListDto>>(entityList);
			var entityListDtos = list.MapTo<List<TicketPriceListDto>>();

			return new PagedResultDto<TicketPriceListDto>(count, entityListDtos);
		}
        /// <summary>
        /// 设置票型价格的启用状态
        /// </summary>
        /// <param name="TicketPriceId">票型价格Id</param>
        /// <param name="IsEnabled">启用状态</param>
        /// <returns></returns>
        public async Task SetPriceEnable(Guid TicketPriceId, bool IsEnabled)
        {
            var entity = await _entityRepository.GetAsync(TicketPriceId);
            entity.IsEnabled = IsEnabled;
            await _entityRepository.UpdateAsync(entity);
        }
    }
}


